package com.dy.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.dy.model.School;
import com.dy.tree.TreeDto;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author dy.huang
 * @date 2020/3/22 23:07
 */
public class TreeUtils {
    /**
     * 父子递归集合 带统计功能
     *
     * @param menuList 、
     * @param parentId 第一个节点的pid
     * @return 、
     */
    public static List<TreeDto> treeMenuModelList(List<TreeDto> menuList, int parentId) {
        List<TreeDto> childMenu = new ArrayList<>();
        for (TreeDto treeDto : menuList) {
            TreeDto dto = new TreeDto();
            dto.setCode(treeDto.getCode());
            dto.setId(treeDto.getId());
            dto.setName(treeDto.getName());
            dto.setPid(treeDto.getPid());
            dto.setValue(treeDto.getValue());
            if (treeDto.getPid() == parentId) {
                List<TreeDto> tree = treeMenuModelList(menuList, treeDto.getId());
                dto.setChildren(tree);
                if (dto.getChildren().size() > 0) {
                    dto.setValue(dto.getChildren().stream().mapToInt(TreeDto::getValue).sum());
                }
                childMenu.add(dto);
            }
        }
        return childMenu;
    }

    /**
     * 获取所有子节点
     *
     * @param menuList list
     * @param parentId 第一个节点的pid
     * @return 、
     */
    public static List<School> treeMenuCountsList(List<School> menuList, long parentId) {
        List<School> childMenu = new ArrayList<>();
        for (School object : menuList) {
            School school = new School();
            BeanUtils.copyProperties(object,school);
            System.out.println("school = " + school);
            if (object.getPid() == parentId){
                List<School> tree = treeMenuCountsList(menuList, object.getId());
                school.setChildren(tree);
                if (school.getChildren().size() > 0) {
                    school.setNum(school.getChildren().stream().mapToInt(School::getNum).sum());
                }
                childMenu.add(school);
            }
        }
        return childMenu;
    }

    /**
     * 获取所有子节点
     *
     * @param menuList list
     * @param parentId 第一个节点的pid
     * @return 、
     */
    public static JSONArray treeMenuList(List<Map<String, Object>> menuList, Object parentId) {
        JSONArray childMenu = new JSONArray();
        for (Map<String, Object> object : menuList) {
            JSONObject jsonMenu = new JSONObject(object);
            Object menuId = jsonMenu.get("id");
            Object pid = jsonMenu.get("pid");
            if (parentId.toString().equals(pid.toString())) {
                JSONArray code = treeMenuList(menuList, menuId);
                jsonMenu.put("children", code);
                childMenu.add(jsonMenu);
            }
        }
        return childMenu;
    }
}
